<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="80%"
      align-center
      :show-close="false"
      destroy-on-close
      draggable
      @open="handleOpen"
      @close="handleClose"
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>项目变更</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>
      <ProjectInfo :projectId="projectId" />
      <div class="bg-white my-[10px]">
        <BaseHead>请选择变更类型</BaseHead>
        <div class="p-[10px]">
          <el-checkbox-group v-model="changeType" @change="typeChange">
            <el-checkbox
              :label="item.name"
              :value="item.code"
              v-for="item in changeTypeList.value"
              :key="item.id"
              :disabled="item.disabled"
            />
          </el-checkbox-group>
        </div>
      </div>
      <el-form :model="editForm" :rules="rules" ref="editFormRef">
        <!-- 留校预算变更 -->
        <div class="bg-white mt-[10px]" v-if="changeType.includes('liuxiaoBudget')">
          <BaseHead style="border-bottom: 0">留校预算变更（单位：万元）</BaseHead>
          <div style="color: red" class="text-right p-[5px]">
            变更量总和必须为零，减少填负数，增加填正数
          </div>
          <el-table
            :data="budgetList"
            class="w-full"
            border
            stripe
            row-key="id"
            default-expand-all
            :tree-props="{ hasChildren: 'hasChild' }"
            show-summary
            :summary-method="summaryFn"
          >
            <el-table-column type="index" label="序号" width="60px" />
            <el-table-column prop="name" label="预算科目" />
            <el-table-column label="调整说明">
              <template #default="{ row }">
                <CommonLabel :value="row.feeLimit" :dataList="feeList.value" /> </template
            ></el-table-column>
            <el-table-column label="留校预算" align="center">
              <el-table-column prop="beforeAlterBudgetFee" label="变更前" />
              <el-table-column prop="beforeAlterBudgetFee" label="可用余额"> </el-table-column>
              <el-table-column prop="budgetFeeChange" label="变更量">
                <template #default="{ row }">
                  <div
                    v-if="row.children.length"
                    :style="{
                      color:
                        parseFloat(row.budgetFeeChange) > 0
                          ? 'red'
                          : parseFloat(row.budgetFeeChange) < 0
                          ? 'blue'
                          : '',
                    }"
                  >
                    {{ row.budgetFeeChange }}
                  </div>
                  <el-input
                    v-model="row.budgetFeeChange"
                    clearable
                    @input="valueChange(row, $event)"
                    v-else
                  />
                </template>
              </el-table-column>
              <el-table-column prop="afterAlterBudgetFee" label="变更后">
                <template #default="{ row }">
                  <span
                    v-if="!row.children?.length"
                    :style="{
                      color:
                        parseFloat(row.afterAlterBudgetFee) > parseFloat(row.beforeAlterBudgetFee)
                          ? 'red'
                          : parseFloat(row.afterAlterBudgetFee) <
                            parseFloat(row.beforeAlterBudgetFee)
                          ? 'blue'
                          : '',
                    }"
                    >{{ row.afterAlterBudgetFee }}</span
                  >
                  <span v-else>{{ row.afterAlterBudgetFee }}</span>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
        <!-- 成员变更 -->
        <div class="bg-white my-[10px]" v-if="changeType.includes('member')">
          <BaseHead style="border-bottom: 0">
            成员变更 <el-button @click="handleAdd">增补成员</el-button></BaseHead
          >
          <el-table :data="memberList" class="w-full" border stripe>
            <el-table-column type="index" label="序号" width="60px" />
            <el-table-column label="成员类型">
              <template #default="{ row }">
                <!-- 根据isOld是否为空判断是否是已经再项目中的成员 不能删除 -->
                <div class="flex items-center" v-if="row.isOld == 0">
                  <span class="no-empty-icon">*</span>
                  <CommonSelect
                    :isFetch="false"
                    :dataList="memberTypeList.value"
                    v-model="row.memberType"
                    valueKey="code"
                    @change="memberTypeChange(row, $event)"
                  />
                </div>
                <CommonLabel :dataList="memberTypeList.value" :value="row.memberType" v-else />
              </template>
            </el-table-column>
            <el-table-column label="姓名">
              <template #default="{ row }">
                <div class="flex items-center" v-if="row.isOld == 0">
                  <span class="no-empty-icon">*</span>
                  <el-autocomplete
                    v-model="row.personName"
                    :fetch-suggestions="personSearch(row)"
                    clearable
                    value-key="name"
                    highlight-first-item
                    @select="selectPerson(row, $event)"
                    @blur="selectPerosnBlur(row, $event)"
                    v-if="row.memberType != 3"
                  >
                    <template #default="{ item }">
                      <span>{{ item.name }}</span>
                      <span class="mx-[10px]">{{ item.account }}</span>
                      <span>{{ item.unitName }}</span>
                    </template>
                  </el-autocomplete>
                  <el-input clearable v-model="row.personName" v-else />
                </div>
                <span v-else>{{ row.personName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="工作单位">
              <template #default="{ row }">
                <template v-if="row.isOld == 0">
                  <CommonTreeSelect
                    :isFetch="false"
                    :dataList="unitList.value"
                    v-model="row.unitId"
                    valueKey="codeColumn"
                    labelKey="valueColumn"
                    v-if="row.memberType != 3"
                  />
                  <el-input clearable v-model="row.unitName" v-else />
                </template>
                <template v-else>
                  <CommonLabel
                    v-if="row.memberType != 3"
                    :dataList="unitList.value"
                    valueKey="codeColumn"
                    labelKey="valueColumn"
                    :value="row.unitId"
                  />
                  <span v-else>{{ row.unitName }}</span>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="职称">
              <template #default="{ row }">
                <CommonTreeSelect
                  :isFetch="false"
                  :dataList="applierTitleList.value"
                  v-model="row.titleId"
                  check-strictly
                  v-if="row.isOld == 0"
                />
                <CommonTreeLabel :value="row.titleId" :dataList="applierTitleList.value" v-else />
              </template>
            </el-table-column>
            <el-table-column label="学位">
              <template #default="{ row }">
                <CommonSelect
                  :isFetch="false"
                  :dataList="degreeList.value"
                  v-model="row.eduDegreeId"
                  valueKey="code"
                  v-if="row.isOld == 0"
                />
                <CommonLabel :value="row.eduDegreeId" :dataList="degreeList.value" v-else />
              </template>
            </el-table-column>
            <el-table-column label="项目角色">
              <template #default="{ row }">
                <CommonSelect
                  :isFetch="false"
                  :dataList="cdTypeList.value"
                  v-model="row.bearTypeId"
                  valueKey="code"
                  v-if="row.isOld == 0"
                />
                <CommonLabel :value="row.bearTypeId" :dataList="cdTypeList.value" v-else />
              </template>
            </el-table-column>
            <el-table-column label="成员状态">
              <template #default="{ row }">
                <CommonSelect
                  :isFetch="false"
                  :dataList="
                    memberStatusList.value.filter((item) =>
                      row.isOld == 1 ? item.code != 2 : item.code == 2
                    )
                  "
                  v-model="row.joinStateId"
                  valueKey="code"
                />
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="100" align="center">
              <template #default="{ row, $index }">
                <el-button
                  type="primary"
                  size="small"
                  plain
                  @click="handleDel($index)"
                  v-if="row.isOld == 0"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 项目委托 -->
        <div class="bg-white mt-[10px]" v-if="changeType.includes('mandatary')">
          <BaseHead>项目委托</BaseHead>
          <BaseTable>
            <tr>
              <td class="td-name">被委托人<span class="no-empty">*</span></td>
              <td style="width: 87.5%" colspan="3">
                <el-form-item label="" prop="mandataryname">
                  <el-autocomplete
                    v-model="editForm.mandataryname"
                    :fetch-suggestions="queryClientPerosn"
                    clearable
                    value-key="name"
                    placeholder="请输入检索关键词"
                    @select="selectClientPerosn"
                    @blur="clientPerosnBlur"
                    style="width: 300px"
                  >
                    <template #default="{ item }">
                      <span>{{ item.name }}</span>
                      <span class="mx-[10px]">{{ item.account }}</span>
                      <span>{{ item.unitName }}</span>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="td-name">委托开始日期<span class="no-empty">*</span></td>
              <td>
                <el-form-item label="" prop="mandatarybegindate">
                  <el-date-picker
                    v-model="editForm.mandatarybegindate"
                    type="date"
                    clearable
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </td>
              <td class="td-name">委托结束日期<span class="no-empty">*</span></td>
              <td>
                <el-form-item label="" prop="mandataryenddate">
                  <el-date-picker
                    v-model="editForm.mandataryenddate"
                    type="date"
                    clearable
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </td>
            </tr>
          </BaseTable>
        </div>
        <!-- 延期变更 -->
        <div class="bg-white mt-[10px]" v-if="changeType.includes('delayFinish')">
          <BaseHead>延期变更</BaseHead>
          <BaseTable>
            <tr>
              <td class="td-name">延期结项至<span class="no-empty">*</span></td>
              <td style="width: 87.5%" colspan="3">
                <el-form-item label="" prop="changePlanEndDate">
                  <el-date-picker
                    v-model="editForm.changePlanEndDate"
                    type="date"
                    clearable
                    value-format="YYYY-MM-DD"
                    style="width: 240px"
                  />
                </el-form-item>
              </td>
            </tr>
          </BaseTable>
        </div>
        <div class="bg-white">
          <BaseTable>
            <tr>
              <td class="td-name">变更证明材料</td>
              <td style="width: 87.5%">
                <FileUpload
                  :uploadUrl="uploadUrl"
                  v-model="fileList"
                  tip=""
                  :limit="1"
                  @change="fileChange"
                />
              </td>
            </tr>
            <tr>
              <td class="td-name">变更原因<span class="no-empty">*</span></td>
              <td>
                <el-form-item label="" prop="alterReason" class="mb-[0px]">
                  <el-input
                    v-model="editForm.alterReason"
                    placeholder="变更原因"
                    type="textarea"
                    show-word-limit
                    maxlength="500"
                  />
                </el-form-item>
              </td>
            </tr>
          </BaseTable>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <!-- <template v-if="verifyRoleType.isKyry()">
              <el-button type="primary" @click="save(-1)" :loading="loading">暂存</el-button>
              <el-button type="primary" @click="save(1)" :loading="loading">提交</el-button>
            </template>
            <template v-if="verifyRoleType.iskycgly()">
              <el-button type="primary" @click="save(-1)" :loading="loading">保存</el-button>
              <el-button
                type="primary"
                @click="save(2)"
                v-if="[-1, 3].includes(Number(checkStatus)) || isAuditor"
                :loading="loading"
                >保存并通过</el-button
              >
            </template> -->
            <el-button
              type="primary"
              @click="save(-1)"
              :loading="loading && submitType == -1"
              :disabled="loading && submitType != -1"
              >{{ verifyRoleType.isKyry() ? "暂存" : "保存" }}</el-button
            >
            <el-button
              type="primary"
              @click="save(1)"
              :loading="loading && submitType == 1"
              :disabled="loading && submitType != 1"
              v-if="verifyRoleType.isKyry()"
              >提交</el-button
            >
            <el-button
              type="primary"
              @click="save(2)"
              v-if="
                verifyRoleType.iskycgly() && ([-1, 3].includes(Number(checkStatus)) || isAuditor)
              "
              :loading="loading && submitType == 2"
              :disabled="loading && submitType != 2"
              >保存并通过</el-button
            >
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import BaseTable from "@/views/project/components/BaseTable.vue";
import FileUpload from "@/views/project/components/FileUpload.vue";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import CommonTreeLabel from "@/views/project/components/CommonTreeLabel.vue";
import CommonTreeSelect from "@/views/project/components/CommonTreeSelect.vue";
import ProjectInfo from "./ProjectInfo.vue";
import { addRecords, recordsDetail } from "@/api/project/zx/xmbg";
import useCommonFetch from "@/hooks/useCommonFetch";
import { getPersonList } from "@/api/project/common";
import { memberDetail, budgetDetail, baseInfo } from "@/api/project/zx/lxxm";
import { ElMessage } from "element-plus";
import { assignObj } from "@/utils/main";
import { verifyRoleType, fomateNegativeNumber, fiexdNumber } from "@/utils/main";
import _ from "lodash";
const memberTypeList = ref([]);
const unitList = ref([]);
const applierTitleList = ref([]);
const degreeList = ref([]);
const cdTypeList = ref([]);
const changeTypeList = ref([]);
const memberStatusList = ref([]);
const feeList = ref([]); //经费调整限制下拉列表
const uploadUrl = `/commonFile/uploadFile?modelName=纵、校项目项目变更证明材料`;
const fileList = ref([]);
const projectId = ref(null);
const projectClass = ref("");
const dialogVisible = ref(false);
const editFormRef = ref();
const changeType = ref([]); //选择的变更类型
const memberList = ref([]);
const budgetList = ref([]);
const detailData = ref({});
const operateId = ref(null);
const isAuditor = ref(false);
const taskId = ref("");
const checkStatus = ref("");
const chargerCode = ref(null); //负责人id
const planEndDate = ref(); //计划结束日期
const loading = ref(false);
const submitType = ref(null);
let oldMemberList = []; //原项目成员列表
//选择的变更类型名称
const changeTypeName = computed(() => {
  const typeName = [];
  changeType.value.forEach((code) => {
    changeTypeList.value.value.forEach((item) => {
      if (item.code == code) {
        typeName.push(item.name);
      }
    });
  });
  return typeName;
});
const editForm = reactive({
  alterFileId: "",
  alterReason: "",
  mandataryname: "", //被委托人姓名
  mandatarycode: "", //被委托人id
  mandatarybegindate: "", //委托开始日期
  mandataryenddate: "", //委托结束日期
  changePlanEndDate: "", //延期至
});
//验证委托开始日期
const validateMandatarybegindate = (rule, value, callback) => {
  if (editForm.mandataryenddate) {
    if (new Date(value).getTime() >= new Date(editForm.mandataryenddate).getTime()) {
      callback(new Error("委托开始日期应早于委托结束日期"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
//验证委托结束日期
const validateMandataryenddate = (rule, value, callback) => {
  if (editForm.mandatarybegindate || planEndDate.value) {
    if (editForm.mandatarybegindate && planEndDate.value) {
      if (
        new Date(value).getTime() <= new Date(editForm.mandatarybegindate).getTime() &&
        new Date(value).getTime() >= new Date(planEndDate.value).getTime()
      ) {
        callback(new Error("委托结束日期要晚于委托开始日期,早于计划完成日期"));
      } else if (new Date(value).getTime() <= new Date(editForm.mandatarybegindate).getTime()) {
        callback(new Error("委托结束日期要晚于委托开始日期"));
      } else if (new Date(value).getTime() >= new Date(planEndDate.value).getTime()) {
        callback(new Error("委托结束日期早于计划完成日期"));
      } else {
        callback();
      }
    } else if (editForm.mandatarybegindate) {
      if (new Date(value).getTime() <= new Date(editForm.mandatarybegindate).getTime()) {
        callback(new Error("委托结束日期要晚于委托开始日期"));
      } else {
        callback();
      }
    } else if (planEndDate.value) {
      if (new Date(value).getTime() >= new Date(planEndDate.value).getTime()) {
        callback(new Error("委托结束日期早于计划完成日期"));
      } else {
        callback();
      }
    }
  } else {
    callback();
  }
};
//验证延期变更时间
const validateChangePlanEndDate = (rule, value, callback) => {
  if (planEndDate.value) {
    if (new Date(value).getTime() <= new Date(planEndDate.value).getTime()) {
      callback(new Error("延期日期应晚于当前计划完成日期！"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const rules = {
  alterReason: [
    {
      required: true,
      message: "变更原因必填",
    },
  ],
  mandataryname: [
    {
      required: true,
      message: "被委托人姓名必填",
    },
  ],
  mandatarybegindate: [
    {
      required: true,
      message: "委托开始日期必填",
    },
    { validator: validateMandatarybegindate, trigger: "blur" },
  ],
  mandataryenddate: [
    {
      required: true,
      message: "委托结束日期必填",
    },
    { validator: validateMandataryenddate, trigger: "blur" },
  ],
  changePlanEndDate: [
    {
      required: true,
      message: "延期结项日期必填",
    },
    { validator: validateChangePlanEndDate, trigger: "blur" },
  ],
};
//获取基础信息
const getBaseInfoData = async () => {
  try {
    const params = {
      proId: projectId.value,
    };
    const res = await baseInfo(params);
    planEndDate.value = res.data.planEndDate;
    chargerCode.value = res.data.chargerCode;
  } catch (error) {
    console.log(error);
  }
};
//获取记录详情
const getDetail = async () => {
  try {
    const res = await recordsDetail(operateId.value);
    detailData.value = res.data;
    const bizProjectAlteration = res.data.bizProjectAlteration;
    checkStatus.value = bizProjectAlteration.checkstatus;
    projectClass.value = bizProjectAlteration.classId;
    changeType.value = bizProjectAlteration.alterType.split(",");
    if (res.data.memberAlterationsList) {
      memberList.value = res.data.memberAlterationsList;
    }
    //如果编辑时返回的预算信息为空 则获取项目预算
    if (res.data.budgetAlterationList) {
      budgetList.value = res.data.budgetAlterationList;
    } else {
      getBudgetDetail();
    }
    //如果变更证明材料id有值
    if (bizProjectAlteration.alterFileId) {
      fileList.value.push({
        name: bizProjectAlteration.fileName,
        id: bizProjectAlteration.alterFileId,
      });
    }
  } catch (error) {
    console.log(error);
  }
};
// 新增
const add = (proId, proClass) => {
  operateId.value = null;
  projectId.value = proId;
  projectClass.value = proClass;
  dialogVisible.value = true;
  changeTypeList.value = useCommonFetch("变更类型（纵、校）");
  getMemberDetail();
  getBudgetDetail();
};
// 编辑
const edit = (id, proId, tId, isAudit) => {
  operateId.value = id;
  projectId.value = proId;
  taskId.value = tId;
  isAuditor.value = isAudit;
  dialogVisible.value = true;
  nextTick(async () => {
    //编辑时先获取项目原始成员列表 用于后面判断成员是否有变更
    await getMemberDetail();
    await getDetail();
    //放这里保证changeType.value有值
    changeTypeList.value = await useCommonFetch("变更类型（纵、校）");
    assignObj(editForm, detailData.value.bizProjectAlteration);
  });
};
defineExpose({ add, edit });
//获取成员信息
const getMemberDetail = async () => {
  const params = {
    proId: projectId.value,
  };
  try {
    const res = await memberDetail(params);
    memberList.value = res.data.bizZxProjectMemberList;
    //成员身上加上isOld属性用户判断是否是已存在的成员
    memberList.value.forEach((item) => {
      item.isOld = 1;
    });
    oldMemberList = _.cloneDeep(memberList.value);
  } catch (error) {
    console.log(error);
  }
};
//获取预算信息
const getBudgetDetail = async () => {
  const params = {
    proId: projectId.value,
  };
  try {
    const res = await budgetDetail(params);
    budgetList.value = res.data.bizProjectBudgetFeeList || [];
    //金额字符串类型转数字类型
    const moneyToNumber = (rows) => {
      for (let i = 0; i < rows.length; i++) {
        //金额为null时默认值给0 字符串转数字类型
        rows[i].beforeAlterBudgetFee = rows[i].beforeAlterBudgetFee
          ? parseFloat(rows[i].beforeAlterBudgetFee)
          : 0;
        rows[i].afterAlterBudgetFee = rows[i].afterAlterBudgetFee
          ? parseFloat(rows[i].afterAlterBudgetFee)
          : 0;
        rows[i].budgetFeeChange = rows[i].budgetFeeChange ? parseFloat(rows[i].budgetFeeChange) : 0;
        if (rows[i].children) {
          moneyToNumber(rows[i].children);
        }
      }
    };
    moneyToNumber(budgetList.value);
  } catch (error) {
    console.log(error);
  }
};
//变更量改变
const valueChange = (row, val) => {
  fomateNegativeNumber(row, "budgetFeeChange", val);
  nextTick(() => {
    //不可调整
    if (row.feeLimit == "nonadjustable") {
      ElMessage({
        message: `此科目额度不可调整`,
        type: "error",
      });
      row.budgetFeeChange = 0;
    }
    //仅可调减
    else if (row.feeLimit == "onlyReduced" && parseFloat(row.budgetFeeChange) > 0) {
      ElMessage({
        message: `此科目额度仅可调减`,
        type: "error",
      });
      row.budgetFeeChange = 0;
    }
    row.afterAlterBudgetFee = fiexdNumber(
      parseFloat(row.beforeAlterBudgetFee) +
        (row.budgetFeeChange && row.budgetFeeChange != "-" ? parseFloat(row.budgetFeeChange) : 0),
      6
    );
    //判断变更后的值是否小于0
    if (row.afterAlterBudgetFee < 0) {
      ElMessage({
        message: `可用余额为${row.beforeAlterBudgetFee},变更量填写不正确！`,
        type: "error",
      });
      row.budgetFeeChange = 0;
      row.afterAlterBudgetFee = fiexdNumber(
        parseFloat(row.beforeAlterBudgetFee) + parseFloat(row.budgetFeeChange),
        6
      );
    }
    const updateParentMoney = (nodes) => {
      return nodes.map((node) => {
        // 如果有子节点，则递归处理子节点
        if (node.children && node.children.length > 0) {
          const updatedChildren = updateParentMoney(node.children);
          const sumFeeChange = updatedChildren.reduce((acc, cur) => {
            return (
              acc +
              (cur.budgetFeeChange && cur.budgetFeeChange != "-"
                ? parseFloat(cur.budgetFeeChange)
                : 0)
            );
          }, 0);
          const sumFeeChangeAfter = updatedChildren.reduce((acc, cur) => {
            return acc + (cur.afterAlterBudgetFee ? parseFloat(cur.afterAlterBudgetFee) : 0);
          }, 0);
          return {
            ...node,
            budgetFeeChange: fiexdNumber(sumFeeChange, 6),
            afterAlterBudgetFee: fiexdNumber(sumFeeChangeAfter, 6),
            children: updatedChildren,
          };
        }
        // 没有子节点则直接返回
        return node;
      });
    };
    budgetList.value = updateParentMoney(budgetList.value);
  });
};
//合计方法
const summaryFn = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index == 0 || index == 2) {
      sums[index] = "";
    } else if (index == 1) {
      sums[index] = "变更合计";
    } else {
      let total = 0;
      data.forEach((item) => {
        total +=
          !item[column.property] || item[column.property] == "-"
            ? 0
            : parseFloat(item[column.property]);
      });
      sums[index] = fiexdNumber(total, 6);
    }
  });
  return sums;
};
//变更类型改变
const typeChange = (val) => {
  if (!val.length) {
    changeTypeList.value.value.forEach((item) => {
      item.disabled = false;
    });
  } else {
    if (val.includes("middleStop")) {
      changeTypeList.value.value.forEach((item) => {
        if (item.code != "middleStop") {
          item.disabled = true;
        }
      });
    } else {
      changeTypeList.value.value.forEach((item) => {
        if (item.code == "middleStop") {
          item.disabled = true;
        }
      });
    }
  }
};
//搜索项目成员
const personSearch = (row) => {
  return async (queryString, cb) => {
    if (queryString.trim() == "") {
      return;
    }
    row.personId = "";
    const params = {
      name: queryString,
    };
    try {
      const res = await getPersonList(params);
      cb(res.data);
    } catch (error) {
      console.log(error);
    }
  };
};
//重置成员数据
const resetPerosn = (row) => {
  row.personName = "";
  row.personId = "";
  row.sexId = "";
  row.unitId = "";
  row.unitName = "";
  row.personCode = "";
};
//项目成员选择框失去焦点
const selectPerosnBlur = (row) => {
  if (!row.personId) {
    resetPerosn(row);
  }
};
//选择的成员类型改变
const memberTypeChange = (row, val) => {
  //选择校外时或者从校外选择校内或学生时 清空成员信息
  if (val == 3 || (val != 3 && row.personId == "")) {
    resetPerosn(row);
  }
};
//选择项目成员改变
const selectPerson = (row, val) => {
  //判断所选成员是否已存在
  let existFlag = false;
  memberList.value.forEach((item) => {
    if (item.personId == val.id) {
      existFlag = true;
    }
  });
  if (existFlag) {
    ElMessage({
      message: "所选人员已存在！",
      type: "error",
    });
    resetPerosn(row);
    return;
  }
  row.personName = val.name;
  row.personId = val.id;
  row.sexId = val.sexId;
  row.unitId = val.unitId;
  row.unitName = val.unitName;
  row.personCode = val.account;
};
//搜索被委托人
const queryClientPerosn = async (queryString, cb) => {
  if (queryString.trim() == "") {
    return;
  }
  editForm.mandatarycode = "";
  const params = {
    name: queryString,
  };
  try {
    const res = await getPersonList(params);
    cb(res.data);
  } catch (error) {
    console.log(error);
  }
};
//选择被委托人
const selectClientPerosn = (val) => {
  //判断选择的被委托人是否是项目负责人
  if (val.id == chargerCode.value) {
    ElMessage({
      message: "被委托人不能是当前项目负责人！",
      type: "error",
    });
    editForm.mandataryname = "";
    editForm.mandatarycode = "";
    return;
  }
  editForm.mandatarycode = val.id;
};
//选择被委托人失去焦点
const clientPerosnBlur = () => {
  if (!editForm.mandatarycode) {
    editForm.mandataryname = "";
    editForm.mandatarycode = "";
  }
};
//初始化一个项目成员 用于添加
const initMemberItem = () => {
  return {
    memberType: memberTypeList.value.value[0].code, //成员类型
    personName: "", //成员姓名
    personId: "", //成员id
    personCode: "", //工号
    sexId: "", //性别
    unitId: "", //单位Id
    unitName: "", //单位名称
    titleId: "", //职称
    eduDegreeId: "", //学位
    bearTypeId: "", //承担类型
    joinStateId: "2", //参与状态
    isOld: 0,
  };
};
//点击增补成员
const handleAdd = () => {
  memberList.value.push(Object.assign({}, initMemberItem()));
};
//点击删除按钮删除一行
const handleDel = (index) => {
  memberList.value.splice(index, 1);
};
//判断成员列表是否有变化

const areArraysEqual = (arr1, arr2) => {
  // 首先比较数组长度
  if (arr1.length !== arr2.length) {
    return false;
  }
  // 然后比较数组中的每个对象的成员状态字段
  for (let i = 0; i < arr1.length; i++) {
    if (!arr1[i].joinStateId !== !arr2[i].joinStateId) {
      return false;
    }
  }
  return true;
};
const emit = defineEmits(["save-success"]);
//保存
const save = async (type) => {
  try {
    submitType.value = type;
    await editFormRef.value?.validate(async (valid) => {
      if (valid) {
        //判断是否选择了变更类型
        if (!changeType.value.length) {
          ElMessage({
            message: "请选择变更类型！",
            type: "error",
          });
          return;
        }
        //根据选择的变更类型 清空未选择的变更类型的值
        if (!changeType.value.includes("mandatary")) {
          editForm.mandataryname = "";
          editForm.mandatarycode = "";
          editForm.mandatarybegindate = "";
          editForm.mandataryenddate = "";
        }
        if (!changeType.value.includes("delayFinish")) {
          editForm.changePlanEndDate = "";
        }
        const params = {
          baseInfos: {
            projectId: projectId.value,
            classId: projectClass.value,
            alterType: changeType.value.join(","),
            alterTypeName: changeTypeName.value.join(","),
            ...editForm,
            submitType: type,
            isAuditor: isAuditor.value,
            taskId: taskId.value,
            checkstatus: checkStatus.value,
          },
        };
        //编辑时传id
        if (operateId.value) {
          params.baseInfos.id = operateId.value;
        }
        if (changeType.value.includes("liuxiaoBudget")) {
          const budgetAlterationList = [];
          let total = 0; //输入的预算金额总和
          let flag = false; //判断是否至少有一项变更量不为0
          budgetList.value.forEach((item) => {
            total +=
              item.budgetFeeChange && item.budgetFeeChange != "-"
                ? parseFloat(item.budgetFeeChange)
                : 0;
            if (item.budgetFeeChange != 0) {
              flag = true;
            }
          });
          const validateFiled = (rows) => {
            for (let i = 0; i < rows.length; i++) {
              if (
                rows[i].budgetFeeChange &&
                rows[i].budgetFeeChange != "-" &&
                rows[i].budgetFeeChange != 0
              ) {
                flag = true;
              }
              validateFiled(rows[i].children);
            }
          };
          validateFiled(budgetList.value);
          if (!flag) {
            ElMessage({
              message: "请填写变更量且变更量不能为0！",
              type: "error",
            });
            return;
          }
          if (total != 0) {
            ElMessage({
              message: "总变更未调平，请修改变更量！",
              type: "error",
            });
            return;
          }
          const getParams = (rows) => {
            for (let i = 0; i < rows.length; i++) {
              budgetAlterationList.push({
                afterAlterBudgetFee: rows[i].afterAlterBudgetFee,
                beforeAlterBudgetFee: rows[i].beforeAlterBudgetFee,
                budgetFeeChange:
                  rows[i].budgetFeeChange != "-" ? parseFloat(rows[i].budgetFeeChange) : 0,
                budgetType: "liuxiao",
                subjectCode: rows[i].code,
              });
              if (rows[i].children) {
                getParams(rows[i].children);
              }
            }
          };
          getParams(budgetList.value);
          params.budgetAlterationList = budgetAlterationList;
        }
        if (changeType.value.includes("member")) {
          //判断成员姓名是否都填写
          const memberNameList = memberList.value.map((item) => item.personName || "");
          if (memberNameList.includes("")) {
            ElMessage({
              message: "成员姓名不能为空！",
              type: "error",
            });
            return;
          }
          //判断成员是否做了变更
          if (areArraysEqual(memberList.value, oldMemberList)) {
            ElMessage({
              message: "成员未做任何变更，请确认是否需要进行成员变更！",
              type: "error",
            });
            return;
          }
          //设置orderId的值
          memberList.value.forEach((item, index) => {
            item.orderId = index + 1;
          });
          params.memberAlterations = memberList.value;
        }
        loading.value = true;
        const res = await addRecords(params);
        if (res.code === 200) {
          ElMessage({
            message: "操作成功！",
            type: "success",
          });
          emit("save-success");
          dialogVisible.value = false;
        }
      }
    });
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
//上传附件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  editForm.alterFileId = ids.join(",");
};
const handleOpen = () => {
  getBaseInfoData();
  memberTypeList.value = useCommonFetch("成员类型");
  unitList.value = useCommonFetch("成果归属单位");
  applierTitleList.value = useCommonFetch("职称");
  degreeList.value = useCommonFetch("学位");
  cdTypeList.value = useCommonFetch("项目-承担角色");
  memberStatusList.value = useCommonFetch("项目-参与状态");
  feeList.value = useCommonFetch("经费调整限制");
};
const handleClose = () => {
  editFormRef.value.resetFields();
  editForm.mandatarycode = "";
  changeType.value = [];
  fileList.value = [];
  memberList.value = [];
  budgetList.value = [];
  isAuditor.value = false;
  taskId.value = "";
  checkStatus.value = "";
  loading.value = false;
};
//监听changeTypeList改变
watch(
  () => changeTypeList.value.value,
  () => {
    if (changeTypeList.value.value) {
      typeChange(changeType.value);
    }
  }
);
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
.base-table {
  border-top: 0;
  tr {
    &:first-child {
      td {
        border-top: 0;
      }
    }
  }
}
:deep(.el-dialog__body) {
  padding-bottom: 55px !important; //受父弹框样式影响 需加这一行
}
</style>
